﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceProcess;
using Frw.Windows.Services.Monitor;
using System.Diagnostics;

namespace Frw.Services.WindowsServices
{
    public class FrwServiceBase : ServiceBase
    {
        private Process m_monitorProcess = null;
        private string m_sectionGroupName = string.Empty;

        public FrwServiceBase()
        {
        }

        public FrwServiceBase(string sectionGroupName)
        {
            m_sectionGroupName = sectionGroupName;
        }

        public ILogger Logger
        {
            get
            {
                return Frw.Logger.GetInstance();
            }
        }

        protected virtual new void OnStart(string[] args)
        {
            base.OnStart(args);

            Logger.Log(LogLevel.Info, string.Format("Service started at {0}", DateTime.Now));
        }

        protected virtual new void OnStop()
        {
            if (m_monitorProcess != null)
            {
                try
                {
                    m_monitorProcess.Kill();

                    Logger.Log(LogLevel.Info, string.Format("Monitor stopped at {0}", DateTime.Now));
                }
                catch (Exception ex)
                {
                    Logger.Log(LogLevel.Info, string.Format("Monitor error {0}", ex.Message));
                }
            }

            Logger.Log(LogLevel.Info, string.Format("Service stopped at {0}", DateTime.Now));

            base.OnStop();
        }

        public bool EnableMonitor(string sectionGroupName)
        {
            bool retValue = false;

            try
            {
                MonitorSection section = MonitorSection.GetSection(sectionGroupName, "MonitorSection");
                if (section != null)
                {
                    string path = section.Path;

                    m_monitorProcess = new Process();
                    m_monitorProcess.StartInfo.FileName = path;
                    m_monitorProcess.StartInfo.WindowStyle = ProcessWindowStyle.Minimized;
                    m_monitorProcess.Start();

                    //m_monitorProcess = Process.Start("Service1 Monitor", path);

                    Logger.Log(LogLevel.Info, string.Format("Monitor started at {0}", DateTime.Now));

                    retValue = true;
                }
            }
            catch (Exception ex)
            {
                Logger.Log(LogLevel.Info, string.Format("Section Monitor error {0}", ex.Message));
            }

            return retValue;
        }
    }
}
